package com.daisuxia.web.service;

import static com.daisuxia.web.pojo.BorrowOrder.STATUS_BFHK;
import static com.daisuxia.web.pojo.BorrowOrder.STATUS_HKZ;
import static com.daisuxia.web.pojo.BorrowOrder.STATUS_YHZ;
import static com.daisuxia.web.pojo.BorrowOrder.STATUS_YYQ;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import net.sf.json.JSONObject;

import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.daisuxia.constant.Constant;
import com.daisuxia.web.dao.IChannelReportDao;
import com.daisuxia.web.dao.IPaginationDao;
import com.daisuxia.web.pojo.BorrowOrder;
import com.daisuxia.web.pojo.ChannelInfo;
import com.daisuxia.web.pojo.ChannelRate;
import com.daisuxia.web.pojo.ChannelReport;
import com.daisuxia.web.util.DateUtil;
import com.daisuxia.web.util.FastJsonUtils;
import com.daisuxia.web.util.PageConfig;

import redis.clients.jedis.JedisCluster;

@Service
public class ChannelReportService implements IChannelReportService {

	@Autowired
	IChannelReportDao channelReportDao;
	@Autowired
	private IPaginationDao paginationDao;
	@Autowired
	JedisCluster jedisCluster;
	@Autowired
	private IChannelInfoService channelInfoService;

	Logger logger = LoggerFactory.getLogger(this.getClass());
	
	public final static String CHANNEL_REPORT = "channel_report";// Redis key前缀

	@Override
	public ChannelReport getChannelReportById(Integer id) {
		return channelReportDao.findChannelById(id);
	}

	@Override
	public PageConfig<ChannelReport> findPage(HashMap<String, Object> params) {
		params.put(Constant.NAME_SPACE, "ChannelReport");
		PageConfig<ChannelReport> pageConfig = new PageConfig<ChannelReport>();
		pageConfig = paginationDao.findPage("findAll", "findAllCount", params,
				"web");
		return pageConfig;
	}

	@Override
	public PageConfig<ChannelReport> findPrPage(HashMap<String, Object> params) {
		params.put(Constant.NAME_SPACE, "ChannelReport");
		PageConfig<ChannelReport> pageConfig = new PageConfig<ChannelReport>();
		pageConfig = paginationDao.findPage("findPrAll", "findPrAllCount",
				params, "web");
		return pageConfig;
	}

	@Override
	public PageConfig<ChannelReport> findSumPage(HashMap<String, Object> params) {
		params.put(Constant.NAME_SPACE, "ChannelReport");
		PageConfig<ChannelReport> pageConfig = new PageConfig<ChannelReport>();
		pageConfig = paginationDao.findPage("findSumAll", "findSumAllCount",
				params, "web");
		return pageConfig;
	}

	@Override
	public Integer findPrParamsCount(Map<String, Object> params) {
		return channelReportDao.findPrAllCount(params);
	}
	
	@Override
	public Integer findParamsCount(Map<String, Object> params) {
		return channelReportDao.findAllCount(params);
	}
	
	@Override
	public List<ChannelReport> getAllPrChannelReports(Map<String, Object> params) {
		// TODO Auto-generated method stub
		return channelReportDao.findPrAll(params);
	}

	@Override
	public List<ChannelReport> getAllChannelReports(Map<String, Object> params) {
		// TODO Auto-generated method stub
		return channelReportDao.findAll(params);
	}

	@Override
	public boolean saveChannelReport(String nowTime) {
		logger.error("saveChannelReport start " + DateUtil.getDateFormat(new Date(),"yyyy-MM-dd HH:mm:ss")+ "nowTime:"+nowTime);
		boolean bool = false;
		Map<String, Object> param = new HashMap<String, Object>();
		ChannelReport channelReport = new ChannelReport();
		String key = CHANNEL_REPORT;
		int c = 1;
		try {
			/* 设置查询时间 */
			
			Calendar cal = Calendar.getInstance();
			/* 判断当前时间是否在凌晨两点之前，是，重新统计前一天,用于补漏定时任务未统计到的数据*/
			Integer checkDate = 0;
			 
			String time = DateUtil.getDateFormat(cal.getTime(),"yyyy-MM-dd HH:mm:ss");
			checkDate=Integer.valueOf(time.substring(11, 13));
			 
			if(checkDate>0&&checkDate<3){
				cal.add(Calendar.DATE, -1);
				jedisCluster.del(key);
			}
			
			String nowDate = DateUtil
					.getDateFormat(cal.getTime(), "yyyy-MM-dd");

			if (nowTime != null) {
				nowDate = nowTime;
			}
			String code = jedisCluster.get(key);
			if(code!=null){
				logger.error("saveChannelReport start 有任务正在执行，以放弃该任务，任务进入时间： " + code);
				return bool;
			}
			jedisCluster.setex(key,10800,time);
		
			param.put("startDate", nowDate);
			//param.put("endDate", nowDate + " 23:59:59");
			param.put("nowDate", cal.getTime());
			
			/*创建分页查询*/
			HashMap<String, Object> params = new HashMap<String, Object>();
			PageConfig<Map<String,Object>> pm = new PageConfig<Map<String,Object>>();
			pm.setTotalPageNum(1);
			params.put(Constant.PAGE_SIZE, "50");
			
			List<ChannelReport> channelIdList = channelReportDao
					.findChannelId();			
			 List<List<ChannelReport>> array=null;
		    if(CollectionUtils.isNotEmpty(channelIdList)){
		    	int pageSize= 100;
          	  int total = channelIdList.size();  
                int pageCount = total % pageSize == 0 ? total / pageSize : total / pageSize + 1;  
           	    array=new   ArrayList<List<ChannelReport>>();
                for(int i = 0; i < pageCount; i++) {  
                    int start = i * pageSize;  
                    int end = start + pageSize > total ? total : start + pageSize;  
                    List<ChannelReport> subList = channelIdList.subList(start, end);  
                    array.add(subList);
                }  
          }
			
			
		   			
		    for (List<ChannelReport> lists : array) {
					Integer[] channelids = new Integer[lists.size()] ;
                        for(int k=0;k<lists.size();k++){
                        	channelids[k]=lists.get(k).getChannelid();
                        	jedisCluster.set("channelReport_"+lists.get(k).getChannelid(), FastJsonUtils.toJson(lists.get(k)).toString());
                        }
						param.put("channelids", channelids);
						// 注册量
						List<Map<String, Object>>  registerCountMap = channelReportDao.findRegisterCount(param);
//						channelReport.setRegisterCount(1);
						for(Map<String,Object> map:registerCountMap){
							Object val = map.get("userFrom"); 
							ChannelReport   channelReporta=(ChannelReport)JSONObject.toBean(JSONObject.fromObject(jedisCluster.get("channelReport_"+val)), ChannelReport.class);
							if(channelReporta!=null){
								channelReporta.setRegisterCount(Integer.valueOf(map.get("count")==null?"0":map.get("count").toString()));
								jedisCluster.set("channelReport_"+channelReporta.getChannelid(), FastJsonUtils.toJson(channelReporta).toString());
							}
						}
//						
						// 实名认证
						List<Map<String, Object>> realNameCountMap = channelReportDao
								.findRealNameCount(param);
						for(Map<String,Object> map:realNameCountMap){
							Object val = map.get("userFrom"); 
							ChannelReport   channelReporta=(ChannelReport)JSONObject.toBean(JSONObject.fromObject(jedisCluster.get("channelReport_"+val)), ChannelReport.class);
							if(channelReporta!=null){
								channelReporta.setAttestationRealnameCount(Integer.valueOf(map.get("count")==null?"0":map.get("count").toString()));
								jedisCluster.set("channelReport_"+channelReporta.getChannelid(), FastJsonUtils.toJson(channelReporta).toString());
							}
						}
				
//						channelReport.setAttestationRealnameCount(realNameCount);
						// 运营商认证
						List<Map<String, Object>> jxlCountMap = channelReportDao.findJXLCount(param);
//						channelReport.setJxlCount(jxlCount);
						for(Map<String,Object> map:jxlCountMap){
							Object val = map.get("userFrom"); 
							ChannelReport   channelReporta=(ChannelReport)JSONObject.toBean(JSONObject.fromObject(jedisCluster.get("channelReport_"+val)), ChannelReport.class);
							if(channelReporta!=null){
								channelReporta.setJxlCount(Integer.valueOf(map.get("count")==null?"0":map.get("count").toString()));
								jedisCluster.set("channelReport_"+channelReporta.getChannelid(), FastJsonUtils.toJson(channelReporta).toString());
							}
						}
				
	
						// 芝麻认证
						List<Map<String, Object>> zhimaCountMap = channelReportDao.findZMCount(param);
//						channelReport.setZhimaCount(zhimaCount);
						for(Map<String,Object> map:zhimaCountMap){
							Object val = map.get("userFrom"); 
							ChannelReport   channelReporta=(ChannelReport)JSONObject.toBean(JSONObject.fromObject(jedisCluster.get("channelReport_"+val)), ChannelReport.class);
							if(channelReporta!=null){
								channelReporta.setZhimaCount(Integer.valueOf(map.get("count")==null?"0":map.get("count").toString()));
								jedisCluster.set("channelReport_"+channelReporta.getChannelid(), FastJsonUtils.toJson(channelReporta).toString());
							}
						}
						// 紧急联系人
						List<Map<String, Object>> contactCountMap = channelReportDao
								.findContactCount(param);
//						channelReport.setContactCount(contactCount);
						for(Map<String,Object> map:contactCountMap){
							Object val = map.get("userFrom"); 
							ChannelReport   channelReporta=(ChannelReport)JSONObject.toBean(JSONObject.fromObject(jedisCluster.get("channelReport_"+val)), ChannelReport.class);
							if(channelReporta!=null){
								channelReporta.setContactCount(Integer.valueOf(map.get("count")==null?"0":map.get("count").toString()));
								jedisCluster.set("channelReport_"+channelReporta.getChannelid(), FastJsonUtils.toJson(channelReporta).toString());
							}
						}
						// 工作信息
						List<Map<String, Object>> companyCountMap = channelReportDao
								.findCompanyCount(param);
//						channelReport.setCompanyCount(companyCount);
						for(Map<String,Object> map:companyCountMap){
							Object val = map.get("userFrom"); 
							ChannelReport   channelReporta=(ChannelReport)JSONObject.toBean(JSONObject.fromObject(jedisCluster.get("channelReport_"+val)), ChannelReport.class);
							if(channelReporta!=null){
								channelReporta.setCompanyCount(Integer.valueOf(map.get("count")==null?"0":map.get("count").toString()));
								jedisCluster.set("channelReport_"+channelReporta.getChannelid(), FastJsonUtils.toJson(channelReporta).toString());
							}
						}
						
						// 银行卡绑定
						List<Map<String, Object>> bankCountMap = channelReportDao.findBankCount(param);
//						channelReport.setAttestationBankCount(bankCount);
						for(Map<String,Object> map:bankCountMap){
							Object val = map.get("userFrom"); 
							ChannelReport   channelReporta=(ChannelReport)JSONObject.toBean(JSONObject.fromObject(jedisCluster.get("channelReport_"+val)), ChannelReport.class);
							if(channelReporta!=null){
								channelReporta.setAttestationBankCount(Integer.valueOf(map.get("count")==null?"0":map.get("count").toString()));
								jedisCluster.set("channelReport_"+channelReporta.getChannelid(), FastJsonUtils.toJson(channelReporta).toString());
							}	
						}
						// 支付宝
						List<Map<String, Object>> alipayCountMap = channelReportDao
								.findAlipayCount(param);
//						channelReport.setAlipayCount(alipayCount);
						for(Map<String,Object> map:alipayCountMap){
							Object val = map.get("userFrom"); 
							
							ChannelReport   channelReporta=(ChannelReport)JSONObject.toBean(JSONObject.fromObject(jedisCluster.get("channelReport_"+val)), ChannelReport.class);
							if(channelReporta!=null){
								channelReporta.setAlipayCount(Integer.valueOf(map.get("count")==null?"0":map.get("count").toString()));
	                        	jedisCluster.set("channelReport_"+channelReporta.getChannelid(), FastJsonUtils.toJson(channelReporta).toString());
							}
						}
						// 授信失败人数
//						List<Map<String, Object>> approveErrorCount = channelReportDao
//								.findApproveErrorCount(param);
//						channelReport.setApproveErrorCount(approveErrorCount);
	
						// 申请借款
						List<Map<String, Object>> borrowApplyCountMap = channelReportDao
								.findBorrowApplyCount(param);
//						channelReport.setBorrowApplyCount(borrowApplyCount);
						for(Map<String,Object> map:borrowApplyCountMap){
							Object val = map.get("userFrom"); 
							ChannelReport   channelReporta=(ChannelReport)JSONObject.toBean(JSONObject.fromObject(jedisCluster.get("channelReport_"+val)), ChannelReport.class);
							if(channelReporta!=null){
								channelReporta.setBorrowApplyCount(Integer.valueOf(map.get("count")==null?"0":map.get("count").toString()));
	                        	jedisCluster.set("channelReport_"+channelReporta.getChannelid(), FastJsonUtils.toJson(channelReporta).toString());
							}
						}
	
						// 申请借款成功
						Integer[] inStatus = new Integer[] { STATUS_HKZ,
								STATUS_BFHK, BorrowOrder.STATUS_YHK,
								BorrowOrder.STATUS_YQYHK, STATUS_YYQ, STATUS_YHZ };
						param.put("inStatus", inStatus);
						List<Map<String, Object>> borrowSucCountMap = channelReportDao
								.findBorrowSucCount(param);
//						channelReport.setBorrowSucCount(borrowSucCount);
						for(Map<String,Object> map:borrowSucCountMap){
							Object val = map.get("userFrom"); 
							ChannelReport   channelReporta=(ChannelReport)JSONObject.toBean(JSONObject.fromObject(jedisCluster.get("channelReport_"+val)), ChannelReport.class);
							if(channelReporta!=null){
								channelReporta.setBorrowSucCount(Integer.valueOf(map.get("count")==null?"0":map.get("count").toString()));
	                        	jedisCluster.set("channelReport_"+channelReporta.getChannelid(), FastJsonUtils.toJson(channelReporta).toString());
							}
						}
	
						// 计算百分比
//						BigDecimal a = new BigDecimal(borrowApplyCount);
//						BigDecimal b = new BigDecimal(borrowSucCount);
//						BigDecimal c = BigDecimal.ZERO;
//						if (borrowApplyCount > 0 && borrowSucCount > 0) {
//							c = b.multiply(new BigDecimal(100)).divide(a, 2,
//									BigDecimal.ROUND_HALF_UP);
//							
//							 
//						}
//						channelReport.setPassRate(c);
						//统计借款率
//						BigDecimal d = new BigDecimal(registerCount);
//						BigDecimal e = BigDecimal.ZERO;
//						if (borrowApplyCount > 0 && registerCount > 0) {
//							e = a.multiply(new BigDecimal(100)).divide(d, 2,
//									BigDecimal.ROUND_HALF_UP);
//						}
//						channelReport.setBorrowRate(e);
						// 放款金额
						List<Map<String, Object>> intoMoneyMap = channelReportDao.findIntoMoney(param);
//						channelReport.setIntoMoney(new BigDecimal(intoMoney));
	
						for(Map<String,Object> map:intoMoneyMap){
							Object val = map.get("userFrom"); 
							ChannelReport   channelReporta=(ChannelReport)JSONObject.toBean(JSONObject.fromObject(jedisCluster.get("channelReport_"+val)), ChannelReport.class);
							if(channelReporta!=null){
								channelReporta.setIntoMoney(new BigDecimal(map.get("moneyAmount")==null?"0":map.get("moneyAmount").toString()));
	                        	jedisCluster.set("channelReport_"+channelReporta.getChannelid(), FastJsonUtils.toJson(channelReporta).toString());
							}
						}
						
						// 新用户放款金额放款金额
						param.put("newcustomerType", "0");
						List<Map<String, Object>> newintoMoneyMap = channelReportDao.findNewIntoMoney(param);
	
						for(Map<String,Object> map:newintoMoneyMap){
							Object val = map.get("userFrom"); 
							ChannelReport   channelReporta=(ChannelReport)JSONObject.toBean(JSONObject.fromObject(jedisCluster.get("channelReport_"+val)), ChannelReport.class);
							if(channelReporta!=null){
								channelReporta.setNewIntoMoney(new BigDecimal(map.get("moneyAmount")==null?"0":map.get("moneyAmount").toString()));
	                        	jedisCluster.set("channelReport_"+channelReporta.getChannelid(), FastJsonUtils.toJson(channelReporta).toString());
							}
						}
						
						// 老用户放款金额放款金额
						param.put("oldcustomerType", "1");
						List<Map<String, Object>> oldintoMoneyMap = channelReportDao.findOldIntoMoney(param);
	
						for(Map<String,Object> map:oldintoMoneyMap){
							Object val = map.get("userFrom"); 
							ChannelReport   channelReporta=(ChannelReport)JSONObject.toBean(JSONObject.fromObject(jedisCluster.get("channelReport_"+val)), ChannelReport.class);
							if(channelReporta!=null){
								channelReporta.setOldIntoMoney(new BigDecimal(map.get("moneyAmount")==null?"0":map.get("moneyAmount").toString()));
	                        	jedisCluster.set("channelReport_"+channelReporta.getChannelid(), FastJsonUtils.toJson(channelReporta).toString());
							}
						}
						
						
						// 统计黑名单
						List<Map<String, Object>> blackUserCountMap = channelReportDao
								.findBlackUserCount(param);
//						channelReport.setBlackUserCount(blackUserCount);
						for(Map<String,Object> map:blackUserCountMap){
							Object val = map.get("userFrom"); 
							ChannelReport   channelReporta=(ChannelReport)JSONObject.toBean(JSONObject.fromObject(jedisCluster.get("channelReport_"+val)), ChannelReport.class);
							if(channelReporta!=null){
								channelReporta.setBlackUserCount(Integer.valueOf(map.get("count")==null?"0":map.get("count").toString()));
	                        	jedisCluster.set("channelReport_"+channelReporta.getChannelid(), FastJsonUtils.toJson(channelReporta).toString());
							}
						}
	
						// 统计每天逾期人数
						List<Map<String, Object>> lateDayCountMap = channelReportDao
								.findlateDayCount(param);
//						channelReport.setLateDayCount(lateDayCount);
	
						for(Map<String,Object> map:lateDayCountMap){
							Object val = map.get("userFrom"); 
							ChannelReport   channelReporta=(ChannelReport)JSONObject.toBean(JSONObject.fromObject(jedisCluster.get("channelReport_"+val)), ChannelReport.class);
							if(channelReporta!=null){
								channelReporta.setLateDayCount(Integer.valueOf(map.get("count")==null?"0":map.get("count").toString()));
	                        	jedisCluster.set("channelReport_"+channelReporta.getChannelid(), FastJsonUtils.toJson(channelReporta).toString());
							}
						}
						 
						
						SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
//						channelReport.setChannelid(channelid);
						
//						
						for(int k=0;k<lists.size();k++){
							Integer channelId = lists.get(k).getChannelid();
							HashMap<String, Object> queryMap = new HashMap<String, Object>();
							HashMap<String, Object> queryMap1 = new HashMap<String, Object>();
							queryMap.put("id", channelId);
							ChannelInfo channelInfo = channelInfoService.findOneChannelInfo(queryMap);
							BigDecimal money = BigDecimal.ZERO;
							
							ChannelReport  channelReportA=(ChannelReport)JSONObject.toBean(JSONObject.fromObject(jedisCluster.get("channelReport_"+channelId)), ChannelReport.class);
							/*判断费率入库时间*/
							int days = DateUtil.getDateFormat(nowDate, "yyyy-MM-dd");
							if(days<0){
								if(channelInfo!=null&&channelInfo.getRateId()!=null){
									queryMap1.put("id", channelInfo.getRateId());
									ChannelRate  channelRate = channelInfoService.findOneChannelRateInfo(queryMap1);
							 		money=new BigDecimal(channelReportA.getRegisterCount()).multiply(channelRate.getChannelRegisterRate())
							 				.add(((channelReportA.getNewIntoMoney()).multiply(channelRate.getChannelNewloanRate())).divide(new BigDecimal(100), 0,
							 						BigDecimal.ROUND_HALF_UP));
								}
							}
							
							channelReportA.setChannelMoney(money);
							channelReportA.setReportDate(sdf.parse(nowDate));
							channelReportDao.deleteByChannelReport(channelReportA);
							channelReportDao.insert(channelReportA);
							jedisCluster.del("channelReport_"+channelId);
			            }
					}
			
			jedisCluster.del(key);
			logger.error("saveChannelReport end " + DateUtil.getDateFormat(new Date(),"yyyy-MM-dd HH:mm:ss")+ "nowTime:"+nowTime);
		} catch (Exception e) {
			logger.error("channek saveReport error", e);
		}
		return true;
	}

	
	
	

}
